<template>
  <q-page class="row index-container q-pa-md">
    <div class="col-xs-12 col-md-4 q-pa-xs setHeight">
      <div class="child full-width full-height">
        <div style="height: 90%">
          <div
            v-if="mainScreenItem.length>0"
            ref="mainScreen"
            class="my_video full-width full-height"
            :id="mainScreenItem[0].id"
          />
        </div>
        <div class="q-ma-xs" style="text-align: center; height: 10%">
          <QBtnGroup outline>
            <QBtn outline color="white" icon="autorenew"/>
            <QBtn outline color="white" icon="videocam" @click.prevent="sendVideo"/>
            <QBtn outline color="white" icon="mic" @click.prevent="sendAudio"/>
            <QBtn outline color="white" icon="volume_up"/>
            <QBtn outline color="white" icon="fast_rewind"/>
            <QBtn
              outline
              color="white"
              :icon="mainVideoPlaying ? `pause_circle_filled` : `play_circle_filled`"
              :disabled="mainScreenItem.length===0"
              @click="() => {
                this.mainVideoPlaying ? this.$refs.mainScreen.getElementsByTagName('video').item(0).pause() :this.$refs.mainScreen.getElementsByTagName('video').item(0).play()
                this.mainVideoPlaying = !this.mainVideoPlaying
              }"
            />
            <QBtn outline color="white" icon="fast_forward"/>
            <QBtn outline color="white" icon="photo_camera" @click.prevent="screenShot" :disabled="mainScreenItem.length===0" />
            <QBtn outline color="white" icon="add_box"/>
            <QBtn outline color="white" icon="description"/>
          </QBtnGroup>
        </div>
      </div>
    </div>
    <div class="col-xs-12 col-md-8 q-pa-xs setHeight">
      <div class="child full-width full-height">
        <p>{{JSON.stringify(this.videoList)}}</p>
        <!-- <div class="my_video full-width full-height" id="main-screen" ref="myVideoView"></div> -->
        <!-- <PageMap @transformUserInGuide="setUserInGuide" @transformUserInRequest="setUserInRequest"></PageMap> -->
      </div>
    </div>
    <div class="col-xs-12 col-md-4 q-pa-xs setHeight">
      <div class="child full-width full-height" ref="videoContainer">
        <div style="height: 90%" class="row">
          <div
            :class="`col-${12 / colsAndRows.cols}`"
            v-for="(video, n) in smallScreenItems"
            :key="n"
            :id="video.id"
            :style="{'width': `${Number(1/colsAndRows.cols * 100).toFixed(2)}%`, 'height':`${Number(1/colsAndRows.rows * 100).toFixed(2)}%`}"
            @click.prevent.stop="attachToMainScreen(video, n)"
          />
        </div>
        <div class="q-ma-xs" style="text-align: center; height: 10%">
          <QBtnGroup outline>
            <QBtn outline color="white" label="四分屏" @click="splitedScreens = 4"/>
            <QBtn outline color="white" label="六分屏" @click="splitedScreens = 6"/>
            <QBtn outline color="white" label="八分屏" @click="splitedScreens = 8"/>
            <QBtn outline color="white" label="九分屏" @click="splitedScreens = 9"/>
          </QBtnGroup>
        </div>
      </div>
    </div>
    <div class="row col-xs-12 col-md-8 q-pa-xs setHeight">
      <div class="col-xs-12 col-md-4 q-pa-xs">
        <div class="child full-width full-height">
          <page-chat-list></page-chat-list>
        </div>
      </div>
      <div class="col-xs-12 col-md-4 q-pa-xs">
        <div class="child full-width full-height">
          <PageGuideList :userInGuide="userInGuide" :userInRequest="userInRequest"></PageGuideList>
        </div>
      </div>
      <div class="col-xs-12 col-md-4 q-pa-xs">
        <div class="child full-width full-height"></div>
      </div>
    </div>
    <QModal v-model="screenShotState" :content-css="{width: `${imgWidth+50}px`, height: `${imgHeight+150}px`}">
      <QModalLayout class="full-width full-height">
        <QToolbar slot="header">
          <QToolbarTitle>截图编辑</QToolbarTitle>
        </QToolbar>
        <div class="q-pa-md">
          <!-- <canvas ref="screenShotCanvas" :width="imgWidth" :height="imgHeight" /> -->
          <CanvasDrawer ref="CanvasDrawer" :width="imgWidth" :height="imgHeight" />
          <!-- <img :src="screenShotImgSrc" style="width: 400px; height: 400px" /> -->
        </div>
        <QToolbar slot="footer">
          <QBtn flat rounded label="确定"/>
          <QBtn flat rounded v-close-overlay label="关闭"/>
        </QToolbar>
      </QModalLayout>
    </QModal>
  </q-page>
</template>

<script>
import { dom, debounce } from 'quasar'
const { css } = dom
import ArMeet from 'ar-meet'
import MeetMixin from '../mixins/MeetMixin'
import PageMap from '../components/PageMap'
import PageGuideList from '../components/PageGuideList'
import PageChatList from '../components/PageChatList'
import CanvasDrawer from '../components/CanvasDrawer'
let Meet = null

// 配置开发者信息
// const devid = '88901874'
const appid = 'anyrtcuIzUANlsv4Xr'
// const appkey = 'ptPg7tvFrgyfF0kYZxf/nNqQxX5LrQ4zyEBw99LWUeE'
const apptoken = 'ddb3e21a35b0566d5bb118292256550e'

export default {
  name: 'PageIndex',

  data: () => ({
    endIndex: 0,
    Meet: null,
    broadCastId: '',
    isHoster: 0,
    roomId: 'gudongglass', // 房间ID
    logs: [], // 日志队列
    cameraList: [], // 视频驶入设备列表
    micphoneList: [], // 音频输入设备列表
    videoList: [],
    userInGuide: '',
    userInRequest: '',
    localVideoEnabled: false,
    localAudioEnabled: false,
    splitedScreens: 4,
    mainVideoPlaying: true,
    screenShotImgSrc: '',
    screenShotState: false,
    imgWidth: 400,
    imgHeight: 400
    // rtmpBaseUrl: `rtmp://${window.location.host.split(':')[0]}/live/`
    // rtmpBaseUrl: `rtmp://test2.goolton.com/live/`
  }),

  mixins: [MeetMixin],

  components: {
    PageMap,
    PageGuideList,
    PageChatList,
    CanvasDrawer
    // MainPlayer,
    // SmallPlayer
    // Player,
    // VideoOperator
  },
  computed: {
    mainScreenItem: function () {
      return this.videoList ? this.videoList.slice(0, 1) : []
    },
    smallScreenItems: function () {
      return this.videoList ? this.videoList.slice(1) : []
    },

    colsAndRows: function () {
      if (this.splitedScreens === 4) {
        return { cols: 2, rows: 2 }
      } else if (this.splitedScreens === 6) {
        return { cols: 3, rows: 2 }
      } else if (this.splitedScreens === 8) {
        return { cols: 4, rows: 2 }
      } else if (this.splitedScreens === 9) {
        return { cols: 3, rows: 3 }
      }
    }
  },
  inject: ['isMobile', 'isTablet'],
  mounted () {
    this.initMeetEngine()
    this.initMeetEventCallback()
    this.joinMeet()
  },
  methods: {
    initMeetEngine () {
      Meet = new ArMeet({
        userId: String(this.$q.cookies.get('userName')),
        userData: '{}',
        // userRole: parseInt(this.isHoster),
        meetMode: 0, // 0 普通 1 主持人模式 2 ZOOM
        logLevel: 'info',
        audioMeet: false,
        autoBitrate: true, // 默认true，true为根据网络状况自适应码流，false为强制指定码率
        videoProfile: 'ARVideoProfile360P'
      })
      // 配置私有云域名
      Meet.configServer('webrtc.goolton.com')
      Meet.initAppInfo(appid, apptoken)
      Meet.setLocalVideoEnable(this.localVideoEnabled)
      Meet.setLocalAudioEnable(this.localAudioEnabled)
      console.info('info', '方法：initEngine：初始化')
    },

    initMeetEventCallback () {
      // 加入房间成功
      Meet.on('join-success', () => {
        console.info('info', '回调：join-success: 加入房间成功')
        this.Meet = Meet
        // 刷新页面离开房间
        window.onbeforeunload = function (e) {
          // 窗口关闭事件,要考虑到滚动条的宽度，一般是20px
          var event = e || window.event
          event.returnValue = '确认是否关闭当前网页' // 点击关闭的时候给提示
        }
        // 退出会议
        window.onunload = function (e) {
          Meet.leaveRTC()
        }
      })

      // 加入房间失败
      Meet.on('join-failed', code => {
        console.info('error', `回调：join-failed: 加入房间失败，错误码${code}`)
      })

      // 远程视频流打开
      Meet.on('stream-subscribed', (peerId, pubId, userData, mediaRender) => {
        console.info('info', `回调：stream-subscribed: 远程人员加入`)
        this.$nextTick(() => {
          this.videoList.push({
            id: 'video-player_' + pubId,
            // width: videoWidth,
            // height: videoHeight,
            isFull: false,
            mediaRender
          })

          this.$nextTick(() => {
            document
              .getElementById('video-player_' + pubId)
              .appendChild(mediaRender)
            setTimeout(() => {
              const videoNode = mediaRender
                .getElementsByTagName('video')
                .item(0)
              if (videoNode) {
                videoNode.setAttribute('controls', true)
                videoNode.setAttribute('muted', false)
                css(videoNode, { height: '100%' })
                console.log(
                  'TCL: initMeetEventCallback -> videoNode',
                  videoNode
                )
              }
            }, 2000)
          })
        })
      })

      // 远程视频流断开
      Meet.on('stream-unsubscribed', (peerId, pubId, userData) => {
        // this.addLog('info', `回调：stream-unsubscribed: 远程人员离开`)
        document.getElementById('video-player_' + pubId) &&
          document.getElementById('video-player_' + pubId).remove()
        this.videoList.map((video, index) => {
          if (video.id === 'video-player_' + pubId) {
            this.videoList.splice(index, 1)
          }
        })
        this.$nextTick(() => {
          // this.handleResize()
        })
      })

      Meet.on('av-status', (isRemote, pubId, audioEnable, videoEnable) => {
        console.log('av-status: ', isRemote, pubId, audioEnable, videoEnable)
      })
      //
      Meet.on('audio-volume', (isRemote, pubId, audioLeval) => {
        // console.log('audio-volume: ', isRemote, pubId, audioLeval);
      })
      //
      Meet.on('network-status', (isRemote, pubId, videoBytes, ARNetQuality) => {
        // console.log('network-status: ', isRemote, pubId, videoBytes, ARNetQuality)
        if (
          isRemote &&
          (ARNetQuality === 'ARNetQualityBad' ||
            ARNetQuality === 'ARNetQualityVBad')
        ) {
          this.$q.notify({
            type: `negative`,
            color: `negative`,
            message: `远端设备网络状态差`,
            timeout: 2000
          })
        }
      })
    },

    joinMeet () {
      Meet.getDevices().then(deviceInfo => {
        this.cameraList = deviceInfo.videoinput
        this.micphoneList = deviceInfo.audioinput

        if (this.cameraList.length === 0) {
          this.$q.dialog({
            title: `错误`,
            message: `没有发现摄像头设备！`
          })
          return
        }

        if (this.micphoneList.length === 0) {
          this.$q.dialog({
            title: `错误`,
            message: `没有发现麦克风设备！`
          })
          return
        }

        this.cameraDeviceId = this.cameraList[this.cameraList.length - 1].value
        this.micphoneDeviceId = this.micphoneList[this.micphoneList.length - 1].value

        console.info('info', `方法：setLocalVideoCapturer: 采集本地媒体流`)
        Meet.setLocalVideoCapturer().then(e => {
          // this.$refs.myVideoView.appendChild(e.mediaRender)
          // document.body.appendChild(e.mediaRender)
          console.log('tag ========', this.roomId)
          Meet.joinRTC(this.roomId)
        })
      })
    },

    attachToMainScreen (video, index) {
      debounce(this.switchVideoes(video, index), 500)
    },

    switchVideoes (video, index) {
      const firstVideo = this.videoList.splice(0, 1, video)
      this.videoList.splice(index + 1, 1, firstVideo[0])
      this.$nextTick(() => {
        const mainNode = document.getElementById(this.videoList[0].id)
        mainNode &&
          mainNode.removeChild(mainNode.childNodes[0]) &&
          mainNode.appendChild(this.videoList[0].mediaRender)
        const anotherNode = document.getElementById(
          this.videoList[index + 1].id
        )
        anotherNode &&
          anotherNode.appendChild(this.videoList[index + 1].mediaRender)
        // 单击事件上大屏与视频播放暂停冲突，显式地恢复播放
        this.videoList[0].mediaRender
          .getElementsByTagName('video')
          .item(0)
          .play()
        this.videoList[index + 1].mediaRender
          .getElementsByTagName('video')
          .item(0)
          .play()
      })
    },

    sendAudio () {
      this.localAudioEnabled = true
      Meet.setLocalAudioEnable(this.localAudioEnabled)
    },

    sendVideo () {
      this.localVideoEnabled = true
      Meet.setLocalVideoEnable(this.localVideoEnabled)
    },

    screenShot () {
      // const canvas = this.$refs.CanvasDrawer.
      const video = this.videoList[0].mediaRender
        .getElementsByTagName('video')
        .item(0)
      // canvas.width = video.width
      this.imgWidth = video.offsetWidth
      this.imgHeight = video.offsetHeight
      // canvas.height = video.height
      this.screenShotState = true
      this.$nextTick(() => {
        const canvasContext = this.$refs.CanvasDrawer.context
        canvasContext.drawImage(video, 0, 0, video.offsetWidth, video.offsetHeight)
      })
      // this.screenShotImgSrc = canvas.toDataURL('image/jpeg')
    }
  }
}
</script>

<style lang="stylus">
@import ('~variables');

.index-container {
  .child {
    border: 1px solid $mediumSpringGreen;
    background-color: $darkSlateGray;
  }

  .setHeight {
    height: 46vh;
  }

  background-color: $deepGreen;
}

.single-row {
  height: 47vh !important;
}

.ar-meet_view {
  padding: 0 20px 20px;
  background-color: #F6F6F6;
}
</style>
